package com.hoapital.outpbillwork.module.controller;

import com.alibaba.fastjson.JSON;
import com.hoapital.outpbillwork.billWorkHandler.*;
import com.hoapital.outpbillwork.module.service.*;
import com.hospital.api.RemoteBillService;
import com.hospital.common.core.constants.OrderConstant;
import com.hospital.common.core.exception.ExceptionHelp;
import com.hospital.common.core.exception.ExceptionPrint;
import com.hospital.common.core.module.controller.vo.Receive;
import com.hospital.common.core.module.controller.vo.ReceiveDate;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author lvyao
 * @description 门诊计费业务控制类
 * @date 2021/2/25
 */
@RestController
@RequestMapping("/billwork")
@Slf4j
public class OutpBillWork {
    @Resource
    private OutpBillItemsTempService outpBillItemsTempService;

    @Resource
    private OutpOrderDescTempService outpOrderDescTempService;

    @Resource
    private InpBillDetailService inpBillDetailService;

    @Resource
    private DrugPrescMasterService drugPrescMasterService;

    @Resource
    private OutpDoctorPrescMasterService outpDoctorPrescMasterService;

    @Resource
    private LabTestItemsService labTestItemsService;

    private RemoteBillService remoteBillService;

    @Autowired
    private final static String outOrInp = "01";

    @PostMapping(value = "/bill", produces = {"application/json;charset=UTF-8"})
    public Tip getRemoteInfo(@RequestBody Receive requestVal, HttpServletRequest request) {
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        Tip retunStr = null;
        List<ReceiveDate> receiveDateList = requestVal.getData();
        if (receiveDateList != null && !receiveDateList.isEmpty()) {
            BillWorkHandler billWorkHandler = null;
            if (requestVal.getTaskId().equals("C")) {
                billWorkHandler = new LabBillJob();
            } else if (requestVal.getTaskId().equals("D")) {
                billWorkHandler = new ExamBillJob();
            } else if (requestVal.getTaskId().equals("A") || requestVal.getTaskId().equals("B")) {
                billWorkHandler = new PrescBillJob();
            }
            BillWorkHandlerStrategy billWorkHandlerStrategy = new BillWorkHandlerStrategy(billWorkHandler);
            if (requestVal.getOutpOrInp().equals(outOrInp)) {
                retunStr = requestVal.getTaskId().equals("B") || requestVal.getTaskId().equals("A") ?
                        billWorkHandlerStrategy.checkOutpOrder(requestVal, outpBillItemsTempService, outpOrderDescTempService, drugPrescMasterService, outpDoctorPrescMasterService) :
                        requestVal.getTaskId().equals("C") ? billWorkHandlerStrategy.checkOutpOrder(requestVal, labTestItemsService, outpBillItemsTempService, outpOrderDescTempService)
                                : billWorkHandlerStrategy.checkOutpOrder(requestVal, outpBillItemsTempService, outpOrderDescTempService);
            } else {
                retunStr = billWorkHandlerStrategy.checkInpOrder(requestVal, inpBillDetailService);
            }
            if (retunStr == null) {
                try {
                    retunStr = billWorkHandlerStrategy.getResult(requestVal, request);
                } catch (Exception e) {
                    stopwatch2.stop();
                    String endTime = DateUtil.getAllTime();
                    ExceptionPrint.printCommString(OrderConstant.OUTP_ITEM_BILL, JSON.toJSONString(requestVal), "1003", e.getMessage(),
                            startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
//                    log.error(e.getMessage());
                    return new ErrorTip("1003", e.getMessage());
                }
            }
        } else {
            retunStr = new ErrorTip("1002", "请求数据中无需要计费的项目，请重新发起申请");
        }
        Tip tip;
        if (retunStr == null) {
//            retunStr = "计费成功";
            tip = new SuccessTip();
        } else {
            tip = retunStr;
        }
        stopwatch2.stop();
        String endTime = DateUtil.getAllTime();
        ExceptionPrint.printCommString(OrderConstant.OUTP_ITEM_BILL, JSON.toJSONString(requestVal), String.valueOf(tip.getCode()), tip.getMessage(),
                startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
        return tip;
    }

    /**
     * 混合项目门诊计费
     *
     * @param requestVal
     * @param request
     * @return
     */
    @PostMapping(value = "/mixbill", produces = {"application/json;charset=UTF-8"})
    public Tip getRemoteInfo(@RequestBody @Valid String requestVal, HttpServletRequest request, BindingResult bindingResult) {
        Tip tip = null;
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        try {
//        log.info("混合项目计费调用入参：" + requestVal);
            BillWorkHandler billWorkHandler = new AllBillJob();
            BillWorkHandlerStrategy billWorkHandlerStrategy = new BillWorkHandlerStrategy(billWorkHandler);

            tip = billWorkHandlerStrategy.getResult(requestVal, request, outpOrderDescTempService);
        } catch (ExceptionHelp exceptionHelp) {
            tip = new ErrorTip("123", "错误！");
            tip.setMessage(exceptionHelp.getMessage());
            tip.setCode(exceptionHelp.getCode());
            if (exceptionHelp.getCode() > 0) {
                return tip;
            }
        } finally {
            stopwatch2.stop();
            String endTime = DateUtil.getAllTime();
            ExceptionPrint.printCommString(OrderConstant.OUTP_MIX_BILL, requestVal, tip == null ? "" : String.valueOf(tip.getCode()), tip == null ? "" : tip.getMessage(),
                    startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
        }
//        log.info(requestVal +"---stopwatch--mixbill总用时: "   + " ---:"+ stopwatch2.getTotalTimeSeconds());
        return tip;
    }

    /**
     * 退费及退结算
     *
     * @param requestVal
     * @return
     */
    @PostMapping(value = "/refundbill", produces = {"application/json;charset=UTF-8"})
    public Tip getRemoteInfo(@RequestBody String requestVal) {
        Tip tip = null;
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        try {
            AllBillJob allBillJob = new AllBillJob();
            tip = allBillJob.refundBill(requestVal, remoteBillService);
        } catch (ExceptionHelp exceptionHelp) {
            tip = new ErrorTip("123", "错误！");
            tip.setMessage(exceptionHelp.getMessage());
            tip.setCode(exceptionHelp.getCode());
            if (exceptionHelp.getCode() > 0) {
                return tip;
            }
        } finally {
            stopwatch2.stop();
            String endTime = DateUtil.getAllTime();
            ExceptionPrint.printCommString(OrderConstant.ALL_BILL_REFUND, requestVal, tip == null ? "" : String.valueOf(tip.getCode()), tip == null ? "" : tip.getMessage(),
                    startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
        }
        return tip;
    }

}
